/**
 * @param {number[][]} grid
 * @return {number}
 */
var matrixScore = function(grid) {
  // 翻转行
  let row = grid.length, col = grid[0].length;
  function reverseRow(i) {
    for(let j = 0; j < col; j++) {
      grid[i][j] = grid[i][j] == 1 ? 0 : 1;
    }
  }
  function reverseCol(j) {
    for(let i = 0; i < row; i++) {
      grid[i][j] = grid[i][j] == 1 ? 0 : 1;
    }
  }
  // 优先翻转行
  for(let i = 0; i < row; i++) {
    if(grid[i][0] == 0) reverseRow(i);
  }
  // 翻转列
  for(let j = 0; j < col; j++) {
    let one = 0;
    for(let i = 0; i < row; i++) {
      if(grid[i][j]) {
        one++;
      }
    }
    if(one <= parseInt(row / 2)) reverseCol(j);
  }
  // 计算结果
  function computeSum(str) {
    let sum = 0;
    for(let i = 0; i < str.length; i++) {
      sum = sum * 2 + parseInt(str[i]);
    }
    return sum;
  }
  let result = 0;
  for(let i = 0; i < row; i++) {
    result += computeSum(grid[i].join(""));
  }
  return result;
};
let grid = [
  [0,0,1,1],
  [1,0,1,0],
  [1,1,0,0]
];
console.log(matrixScore(grid));
